import cv2
import numpy as np
import urllib.request

stream = urllib.request.urlopen('http://10.2.131.222:5555/')
total_bytes = b''
while True:
    total_bytes += stream.read(1024)
    b = total_bytes.find(b'\xff\xd9')  # JPEG end
    if not b == -1:
        a = total_bytes.find(b'\xff\xd8')  # JPEG start
        jpg = total_bytes[a:b + 2]  # actual image
        total_bytes = total_bytes[b + 2:]  # other informations

        # decode to colored image ( another option is cv2.IMREAD_GRAYSCALE )
        img = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.IMREAD_COLOR)

        cv2.imshow('Window name', img)  # display image while receiving data
        if cv2.waitKey(1) == 27:  # if user hit esc
            break
cv2.destroyWindow('Window name')

# import cv2
# import numpy as np
#
# # 调用usb摄像头
#
# cap = cv2.VideoCapture('http://10.2.131.222:5555/')
#
# # 显示
# while True:
#     ret, frame = cap.read()
#     if ret == True:
#         new_video = cv2.flip(frame, 0)
#         #视频旋转cv2.flip(frame, 1)第一个参数表示要旋转的视频
#         # 第二个参数表示旋转的方向，0表示绕x轴旋转，大于0的数表示绕y轴旋转，小于0的负数表示绕x和y轴旋转。
#
#     cv2.imshow("window_before", frame)
#     # cv2.imshow("window_after", new_video)
#     # 如果输入 esc 退出程序
#     boardkey = cv2.waitKey(1) & 0xFF
#     if boardkey == 27:
#         break
# # 关闭
# cap.release()
# cv2.destroyAllWindows()
